package net.lab1024.sa.admin.module.business.erp.sao.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.admin.module.business.erp.prp.dao.PrpordaDao;
import net.lab1024.sa.admin.module.business.erp.sao.dao.SaordDao;
import net.lab1024.sa.admin.module.business.erp.sao.dao.SaordaDao;
import net.lab1024.sa.admin.module.business.erp.sao.dao.SnordaDao;
import net.lab1024.sa.admin.module.business.erp.prp.domain.entity.PrpordaEntity;
import net.lab1024.sa.admin.module.business.erp.sao.domain.entity.SaordEntity;
import net.lab1024.sa.admin.module.business.erp.sao.domain.entity.SaordaEntity;
import net.lab1024.sa.admin.module.business.erp.sao.domain.entity.SnordaEntity;
import net.lab1024.sa.admin.module.business.erp.sao.domain.form.SaordAddForm;
import net.lab1024.sa.admin.module.business.erp.sao.domain.form.SaordQueryForm;
import net.lab1024.sa.admin.module.business.erp.sao.domain.form.SaordUpdateForm;
import net.lab1024.sa.admin.module.business.erp.sao.domain.vo.SaordVO;
import net.lab1024.sa.admin.module.business.erp.sao.domain.vo.SaordaVO;
import net.lab1024.sa.admin.module.business.erp.inv.domain.vo.TargetVo;
import net.lab1024.sa.base.common.code.ErpErrorCode;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SaordService {

    @Resource
    private SaordDao saordDao;
    @Resource
    private SaordaDao saordaDao;
    @Resource
    private PrpordaDao prpordaDao;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private SnordaDao snordaDao;


    /**
     * 分页查询
     */
    public PageResult<SaordVO> queryPage(SaordQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<SaordVO> list = saordDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 添加
     */
    @Transactional
    public ResponseDTO<Long> add(SaordAddForm addForm) {
        SaordEntity saordEntity = SmartBeanUtil.copy(addForm, SaordEntity.class);
        saordDao.insert(saordEntity);
        List<SaordaEntity> saordaEntities = SmartBeanUtil.copyList(addForm.getLista(), SaordaEntity.class);
        for (SaordaEntity saordaEntity : saordaEntities) {
            saordaEntity.setId(saordEntity.getId());
            saordaDao.insert(saordaEntity);
        }
        return ResponseDTO.ok(saordEntity.getId());
    }

    /**
     * 更新
     */
    @Transactional
    public ResponseDTO<String> update(SaordUpdateForm updateForm) {
        SaordEntity saordEntity = SmartBeanUtil.copy(updateForm, SaordEntity.class);
        if (saordDao.updateById(saordEntity) == 0) {
            throw new RuntimeException("数据已被修改，刷新后重试！");
        }
        saordaDao.deleteById(saordEntity.getId());
        List<SaordaEntity> saordaEntities = SmartBeanUtil.copyList(updateForm.getLista(), SaordaEntity.class);
        for (SaordaEntity saordaEntity : saordaEntities) {
            saordaDao.insert(saordaEntity);
        }
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        saordDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }



    @Transactional
    public ResponseDTO<String> delete(Long id) {

        List<PrpordaEntity> prpordaEntities = prpordaDao.selectList(new LambdaQueryWrapper<PrpordaEntity>().eq(PrpordaEntity::getBaseId, id));
        if (!prpordaEntities.isEmpty()){
            return ResponseDTO.error(ErpErrorCode.PARAM_ERROR,"存在生产计划，禁止删除！");
        }



        List<SnordaEntity> snordaEntities = snordaDao.selectList(new LambdaQueryWrapper<SnordaEntity>().eq(SnordaEntity::getBaseId, id));
        if (!snordaEntities.isEmpty()){
            return ResponseDTO.error(ErpErrorCode.PARAM_ERROR,"存在发货通知单，禁止删除！");
        }


        saordDao.deleteById(id);
        saordaDao.deleteById(id);
        return ResponseDTO.ok();
    }

    public ResponseDTO<SaordVO> info(Long id) {
        SaordEntity saordEntity = saordDao.selectById(id);
        SaordVO copy = SmartBeanUtil.copy(saordEntity, SaordVO.class);
        List<SaordaEntity> saordaEntities = saordaDao.selectList(new LambdaQueryWrapper<SaordaEntity>().eq(SaordaEntity::getId, id));
        List<SaordaVO> saordaVOS = SmartBeanUtil.copyList(saordaEntities, SaordaVO.class);


        ArrayList<TargetVo> targetVob = new ArrayList<>();
        for (SaordaVO puordaVO : saordaVOS) {
            if (puordaVO.getBaseId() != null) {
                TargetVo targetVo = new TargetVo();
                targetVo.setId(puordaVO.getBaseId());
                targetVo.setLineNum(puordaVO.getBaseLineNum());
                targetVo.setItemId(puordaVO.getItemId());
                targetVo.setItemName(puordaVO.getItemName());
                targetVo.setQty(puordaVO.getQty());
                targetVob.add(targetVo);
            }
        }

        List<PrpordaEntity> prpordaEntities = prpordaDao.selectList(new LambdaQueryWrapper<PrpordaEntity>().eq(PrpordaEntity::getBaseId, id));

        ArrayList<TargetVo> targetVoc = new ArrayList<>();
        for (PrpordaEntity item : prpordaEntities) {
            TargetVo targetVo = new TargetVo();
            targetVo.setId(item.getId());
            targetVo.setLineNum(item.getLineNum());
            targetVo.setItemId(item.getItemId());
            targetVo.setItemName(item.getItemName());
            targetVo.setQty(item.getQty());
            targetVoc.add(targetVo);
        }

        copy.setLista(saordaVOS);
        copy.setListb(targetVob);
        copy.setListc(targetVoc);
        return ResponseDTO.ok(copy);
    }

    public ResponseDTO<SaordVO> infoUnexecute(Long id) {
        SaordEntity saordEntity = saordDao.selectById(id);
        SaordVO copy = SmartBeanUtil.copy(saordEntity, SaordVO.class);


        List<SaordaVO> puordaVOList = saordaDao.infoUnexecute(id);

        copy.setLista(puordaVOList);
        return ResponseDTO.ok(copy);
    }

    public ResponseDTO<SaordVO> infoUnexecuteBack(Long id) {
        SaordEntity saordEntity = saordDao.selectById(id);
        SaordVO copy = SmartBeanUtil.copy(saordEntity, SaordVO.class);
        List<SaordaVO> puordaVOList = saordaDao.infoUnexecuteBack(id);
        copy.setLista(puordaVOList);
        return ResponseDTO.ok(copy);
    }

    public Boolean checkVersion(Long baseId, Integer baseVersion) {
        return saordDao.selectOne(new LambdaQueryWrapper<SaordEntity>().eq(SaordEntity::getId, baseId).eq(SaordEntity::getVersion, baseVersion)) != null;
    }

    public Boolean upDateVesrion(Long baseId, Integer baseVersion) {
        SaordEntity saordEntity = saordDao.selectOne(new LambdaQueryWrapper<SaordEntity>().eq(SaordEntity::getId, baseId).eq(SaordEntity::getVersion, baseVersion));
        if (saordEntity == null) return false;
        return saordDao.updateById(saordEntity) != 0;
    }


    public void print(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {


        // 1.文件的输入流
        InputStream resourceAsStream = SaordService.class.getClassLoader().getResourceAsStream("jasper/Blank_A4.jasper");

        Connection connection = null;

        try {
             connection = jdbcTemplate.getDataSource().getConnection();

            // 2.创建JasperPrint,向jasper文件中填充数据
            Map parameters = new HashMap<>();
            parameters.put("id", id);

            // 3.将JasperPrint已PDF的形式输出
            JasperPrint jasperPrint = JasperFillManager.fillReport(resourceAsStream, parameters, connection);
            JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        } catch (JRException | SQLException e) {

            e.printStackTrace();

        } finally {

            connection.close();
            resourceAsStream.close();
        }


    }
}
